/*
 * @Author: 一路向阳 tt_sunzhenfeng@163.com
 * @Date: 2024-05-23 21:14:23
 * @LastEditors: 一路向阳 tt_sunzhenfeng@163.com
 * @LastEditTime: 2024-05-25 22:39:59
 * @FilePath: \vue3_nuxt_demo\server\api\note\notebook.get.ts
 * @Description: 获取用户文集接口
 */
import { responseJson, getLoginUid } from '@/server/utils/helper';
import { getDB } from '@/server/utils/db';

/**
 * 1、判断用户是否登录
 * 2、已登录则获取用户的文集
 */

export default defineEventHandler(
  async (event) => {
    //判断用户登录
    const uid = getLoginUid(event);

    // 判断用户id
    if (uid === 0) {
      setResponseStatus(event, 401);
      return responseJson(401,{
        success: false,
        msg: '请先登录'
      });
    }

    // 数据库交互
    const { find, close } = getDB();

    // 查询
    const con = find();

    try {
      
      //获取用户文集
      const [rows] = await con.execute(
        'SELECT * FROM `notebooks` WHERE `uid`=? ORDER BY `id` DESC',
        [uid]
      );

      return  responseJson(200, {
        success: true,
        msg: '获取成功',
        data: rows
      });
    }
    catch (error){
      
      setResponseStatus(event,500);

      return responseJson(500,{
        success: false,
        msg: '服务器错误',
        error: error
      });
    }
    finally {
      // 释放连接
      close();
    }

  }
);